import { ref } from 'vue';
import api from 'axios';
import { uivBaseVOAPI } from 'src/util/UivBaseConst'

export interface OptionTypeItem {
  id: number,
  label: string,
  children: OptionTypeItem[]
}

export function useSelectBoxOption () {
  //类型数据表
  let optionTypeTbl = ref<OptionTypeItem[]>([]);

  //增加选项
  const addSelectBoxOptionTbl = (oid: number) => {
    let index = optionTypeTbl.value.findIndex((item) => (item.id === oid));
    if (index === -1) {
      let item: OptionTypeItem = {
        id: oid,
        label: '',
        children: []
      };
      optionTypeTbl.value.push(item);
    }
  };

  //更新optionshuju
  const updateSelectBoxOptionTbl = (node: OptionTypeItem) => {
    let index = optionTypeTbl.value.findIndex((item) => (item.id === node.id));
    if (index > -1) {
      optionTypeTbl.value[index].label = node.label;
      node.children.forEach((el) => {
        optionTypeTbl.value[index].children.push(el);
      })
    }
  };

  //读取数据
  const getSelectBoxOptionTbl = (oid: number): OptionTypeItem | null => {
    let index = optionTypeTbl.value.findIndex((item: OptionTypeItem) => (item.id === oid));
    if (index === -1) {
      return optionTypeTbl.value[index];
    }

    return null;
  }

  //从数据库中读取数据
  const generateSelectBoxOptionTbl = () => {
    optionTypeTbl.value.forEach((item) => {
      api.post(uivBaseVOAPI.UIV_DICT_TYPE_VO_TREE, {
        id: item.id
      }).then((res: any) => {
        if (res.data.message === 'Success') {
          let list: OptionTypeItem[] = res.data.data;

          //console.log(list);
          list.forEach((el) => {
            updateSelectBoxOptionTbl(el);
          })
        }
      });
    })
  }

  //释放数据
  const releaseSelectBoxOptionTbl = () => {
    optionTypeTbl.value.length = 0;
  }

  return {
    optionTypeTbl,
    addSelectBoxOptionTbl,
    getSelectBoxOptionTbl,
    generateSelectBoxOptionTbl,
    releaseSelectBoxOptionTbl
  }
}
